package com.radiosamhan.ryoko;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import android.util.Log;

public class UdpServer extends Thread {

	private DatagramSocket _socket = null;
	private DatagramPacket _packet = null;
	private byte[] _buffer = new byte[1024];
	private Boolean _stopped = false;

	public void interrupt() {
		super.interrupt();
		_stopped = true;
		Log.d("UDP", "UDP server stopped.");
		_socket.close();
	}

	public void run() {
		Log.d("UDP", "Running UDP Server at port 6667...");
		try {
			_socket = new DatagramSocket(6667);
		} catch (SocketException e) {
			Log.d("UDP", "Error creating DatagramSocket.");
		}
		_packet = new DatagramPacket(_buffer, _buffer.length);
		Log.d("UDP", "Receiving UDP packet...");
		try {
			while (!_stopped) {
				_socket.receive(_packet);
				String data = new String(_packet.getData());
				data = data.substring(0, _packet.getLength());
				Log.d("UDP", "Received UDP packet: " + data);
			}
		} catch (InterruptedIOException e) {
			Thread.currentThread().interrupt();
			Log.d("UDP", "Interupted IO Exception.");
		} catch (IOException e) {
			if (!_stopped) {
				Log.d("UDP", "Error receiving DatagramPacket.");
			}
		}
	}

}
